﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Security;
using System.Text;

namespace FTPComm
{
    public static class FTP
    {
        /// <summary> 
        /// Copy a file from FTP server to local 
        /// </summary> 
        /// <param name="sourceFilename">Target filename, if required </param> 
        /// <param name="localFilename">Full path of the local file </param> 
        /// <returns> </returns> 
        /// <remarks>Target can be blank (use same filename), or just a filename 
        ///// (assumes current directory) or a full path and filename </remarks> 
        //public static bool Download(string sourceFilename, string localFilename, bool PermitOverwrite)
        //{
        //    //2. determine target file 
        //    FileInfo fi = new FileInfo(localFilename);
        //    return this.Download(sourceFilename, fi, PermitOverwrite);
        //}

        ////Version taking an FtpFileInfo 
        //public bool Download(FtpFileInfo file, string localFilename, bool permitOverwrite)
        //{
        //    return this.Download(file.FullName, localFilename, permitOverwrite);
        //}

        ////Another version taking FtpFileInfo and FileInfo 
        //public bool Download(FtpFileInfo file, FileInfo localFI, bool permitOverwrite)
        //{
        //    return this.Download(file.FullName, localFI, permitOverwrite);
        //}

        //Version taking string/FileInfo 
        public static bool Download(string sourceFilename, FileInfo targetFI, bool permitOverwrite)
        {
            //1. check target 
            if (targetFI.Exists && !(permitOverwrite))
            {
                throw (new ApplicationException("Target file already exists"));
            }

            //2. check source 
            string target = "";
            if (sourceFilename.Trim() == "")
            {
                throw (new ApplicationException("File not specified"));
            }
            //else if (sourceFilename.Contains("/"))
            //{
            //    //treat as a full path 
            //    target = AdjustDir(sourceFilename);
            //}
            //else
            //{
            //    //treat as filename only, use current directory 
            //    target = CurrentDirectory + sourceFilename;
            //}

            string Hostname = "";
            string URI = Hostname + target;

            Uri ftpUri = new Uri("ftp://192.168.1.50/ligang/安全法.rar");
            //3. perform copy 
            System.Net.FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUri); //GetRequest(URI);

            //Set request to download a file in binary mode 
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;

            //open request and get response stream 
            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file 
                    using (FileStream fs = targetFI.OpenWrite())
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded 
                            fs.Close();
                            //delete target file as it's incomplete 
                            targetFI.Delete();
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }


            return true;
        }

        public static bool Download(string Uri)
        {
            bool issuccess;
            try
            {
                Uri ftpUri = new Uri(Uri);
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
                FtpWebResponse ftpResponse = null;
                string filename = Uri.Substring(Uri.LastIndexOf("/") + 1);
                FileStream ftpfile = new FileStream("C://" + filename, FileMode.Create);
                //ftpRequest.Credentials = new NetworkCredential("liupeng", "liupeng");
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpRequest.UseBinary = true;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpstream = ftpResponse.GetResponseStream();
                byte[] ftpbyte = new byte[2048];
                int readcout = 0;
                readcout = ftpstream.Read(ftpbyte, 0, 2048);
                while (readcout > 0)
                {
                    ftpfile.Write(ftpbyte, 0, readcout);
                    readcout = ftpstream.Read(ftpbyte, 0, 2048);
                }
                ftpfile.Close();
                ftpResponse.Close();
                ftpstream.Close();
                issuccess = true;
            }
            catch (Exception ex)
            {
                issuccess = false;
                Console.WriteLine(ex);
            }
            return issuccess;
        }

        public static bool Download()
        {
            Uri ftpUri = new Uri("ftp://192.168.1.50/ligang/安全法.rar");
            string ftp = "d.sql";
            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
            FtpWebResponse ftpResponse = null;

            FileStream ftpfile = new FileStream("E://WinCE//FtpCode//安全法.rar", FileMode.Create);
            ftpRequest.Credentials = new NetworkCredential("liupeng", "liupeng");
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpRequest.UseBinary = true;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            Stream ftpstream = ftpResponse.GetResponseStream();
            byte[] ftpbyte = new byte[2048];
            int readcout = 0;
            readcout = ftpstream.Read(ftpbyte, 0, 2048);
            while (readcout > 0)
            {
                ftpfile.Write(ftpbyte, 0, readcout);
                readcout = ftpstream.Read(ftpbyte, 0, 2048);
            }
            ftpfile.Close();
            ftpResponse.Close();
            ftpstream.Close();
            return true;
        }

        private static void Upload(string filename)
        {
            string ftpServerIP = "";
            string ftpUserID = "";
            SecureString ftpPassword = new SecureString();


            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(
                      "ftp://" + ftpServerIP + "/" + fileInf.Name));

            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

            reqFTP.KeepAlive = false;

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 使用二进制传输流.
            reqFTP.UseBinary = true;

            reqFTP.ContentLength = fileInf.Length;

            // 将缓冲区大小设置为 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            FileStream fs = fileInf.OpenRead();

            try
            {
                Stream strm = reqFTP.GetRequestStream();

                contentLen = fs.Read(buff, 0, buffLength);

                while (contentLen != 0)
                {
                    // 通过FTP上传流
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // 用完了流要关闭
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message, "Upload Error");
            }
        }

        /// <summary>
        /// 下载FTP服务器上的文件
        /// </summary>
        /// <param name="Uri">FTP服务器文件地址</param>
        /// <param name="filename">下载本地文件地址</param>
        /// <returns>bool</returns>
        public static bool Download(string Uri, string filename)
        {
            bool issuccess;
            try
            {
                Uri ftpUri = new Uri(Uri);
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
                FtpWebResponse ftpResponse = null;
                //  string filename = Uri.Substring(Uri.LastIndexOf("/") + 1);
                FileStream ftpfile = new FileStream(filename, FileMode.Create);
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpRequest.UseBinary = true;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                Stream ftpstream = ftpResponse.GetResponseStream();
                byte[] ftpbyte = new byte[2048];
                int readcout = 0;
                readcout = ftpstream.Read(ftpbyte, 0, 2048);
                while (readcout > 0)
                {
                    ftpfile.Write(ftpbyte, 0, readcout);
                    readcout = ftpstream.Read(ftpbyte, 0, 2048);
                }
                ftpfile.Close();
                ftpResponse.Close();
                ftpstream.Close();
                issuccess = true;
            }
            catch (Exception ex)
            {
                issuccess = false;
                Console.WriteLine(ex);
            }
            return issuccess;
        }

        /// <summary>
        /// 向FTP服务器上传文件
        /// </summary>
        /// <param name="ftpServerIP">FTP服务器地址</param>
        /// <param name="fullfilename">本地文件地址</param>
        /// <returns>bool</returns>
        public static bool Upload(string ftpServerIP, string fullfilename)
        {
            bool issuccess;
            try
            {
                FileInfo fileInf = new FileInfo(fullfilename);
                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(
                          "ftp://" + ftpServerIP + "/" + fileInf.Name));

                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 使用二进制传输流.
                reqFTP.UseBinary = true;
                reqFTP.ContentLength = fileInf.Length;
                // 将缓冲区大小设置为 2kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                FileStream fs = fileInf.OpenRead();

                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    // 通过FTP上传流
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 用完了流要关闭
                strm.Close();
                fs.Close();
                issuccess = true;
            }
            catch (Exception ex)
            {
                issuccess = false;
                Console.WriteLine(ex.Message, "Upload Error");
            }
            return issuccess;
        }
    }
}
